<script>
import { Plus } from "@element-plus/icons-vue";
import { deleteFileApi, downloadFileApi, getFileApi, uploadFileApi } from "@/api/index.js";
import FormData from "form-data";

export default {
  name: "ImageUploadComponent",
  components: { Plus },
  props: {
    uploadAuto: {
      type: Boolean,
      default: true
    },
    src: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      image: ""
    };
  },
  created() {
    this.getImage();
  },
  methods: {
    selectPicture() {
      this.$refs.imageRef.click();
    },
    getPicture() {
      this.deleteImage(this.src);
      this.image = URL.createObjectURL(this.$refs.imageRef.files[0]);
      if (this.uploadAuto) {
        this.upload();
      }
    },
    upload() {
      if (this.image) {
        const form = new FormData();
        form.append("file", this.$refs.imageRef.files[0]);
        uploadFileApi(form).then(res => {
          this.$message.success("上传成功");
          this.$emit("upload", { fileName: res });
        }).catch(error => {
          this.$message.error(error);
        });
      } else {
        this.$message.error("你还没有选择图片");
      }
    },
    getImage() {
      console.log("开始下载图片", this.src);
      if (this.src) {
        downloadFileApi(this.src).then(res => {
          const { filename } = res;
          getFileApi(filename).then(image => {
            console.log("下载图片完成");
            this.image = window.URL.createObjectURL(image.data);
          });
        });
      }
    },
    deleteImage(name) {
      if(name) {
        deleteFileApi(name).then(() => {
          console.log("删除成功", name);
        });
      }
    }
  }
};
</script>

<template>
  <div class="image-div">
    <div class="my-img" @click="selectPicture">
      <img v-if="image" :src="image" alt="" class="avatar">
      <el-icon v-else class="avatar-uploader-icon">
        <Plus />
      </el-icon>
    </div>
    <input ref="imageRef" type="file" accept=".png,.jpg,jpeg" style="display: none" @change="getPicture">
    <el-button v-if="!uploadAuto" type="primary" style="width: 100%;margin-top: 5px" @click="upload">上传</el-button>
  </div>
</template>

<style scoped>
.my-img {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.my-img:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.image-div {
  width: 100px;
  text-align: center;
}
</style>
